#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
RPA框架GUI应用主程序
"""

import sys
import os
import traceback

# 配置基本日志记录（在导入其他模块之前）
print("正在启动RPA框架GUI应用...")
print(f"Python版本: {sys.version}")

# 添加项目父目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
print(f"当前文件目录: {current_dir}")
project_root = os.path.dirname(os.path.dirname(current_dir))  # d:\ceshi\cj
sys.path.insert(0, project_root)
sys.path.insert(0, os.path.dirname(current_dir))  # 添加rpa_framework目录
print(f"已添加项目根目录到Python路径: {project_root}")
print(f"已添加rpa_framework目录到Python路径: {os.path.dirname(current_dir)}")
print(f"当前Python路径: {sys.path}")

from PyQt5.QtWidgets import QApplication, QSplashScreen, QMessageBox
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QPixmap, QFont

# 优化日志处理
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("rpa.gui.app")

# 导入主窗口类
try:
    # 确保正确导入所有必要的模块
    import sys
    import os
    import traceback
    
    # 确保rpa_framework在Python路径中
    current_dir = os.path.dirname(os.path.abspath(__file__))
    rpa_framework_dir = os.path.dirname(current_dir)
    if rpa_framework_dir not in sys.path:
        sys.path.insert(0, rpa_framework_dir)
    
    logger.info(f"当前目录: {current_dir}")
    logger.info(f"rpa_framework目录: {rpa_framework_dir}")
    logger.info(f"Python路径: {sys.path}")
    
    # 尝试直接导入MainWindow类，忽略可能的内部导入错误
    try:
        from rpa_framework.gui.main_window import RPAMainWindow
        logger.info("成功导入RPAMainWindow")
    except ImportError as e:
        logger.error(f"直接导入失败: {e}")
        
        # 尝试直接从文件导入，绕过部分导入问题
        main_window_path = os.path.join(current_dir, "main_window.py")
        if os.path.exists(main_window_path):
            logger.info(f"尝试直接从文件导入: {main_window_path}")
            import importlib.util
            spec = importlib.util.spec_from_file_location("main_window", main_window_path)
            main_window_module = importlib.util.module_from_spec(spec)
            sys.modules["main_window"] = main_window_module
            try:
                spec.loader.exec_module(main_window_module)
                RPAMainWindow = main_window_module.RPAMainWindow
                logger.info("成功从文件直接导入RPAMainWindow")
            except Exception as import_e:
                logger.error(f"从文件直接导入失败: {import_e}")
                logger.debug(f"详细错误:\n{traceback.format_exc()}")
                raise
        else:
            logger.error(f"main_window.py文件不存在: {main_window_path}")
            raise
            
except Exception as e:
    logger.error(f"导入RPAMainWindow失败: {e}")
    logger.debug(f"详细导入错误:\n{traceback.format_exc()}")
    
    # 创建一个简单的替代窗口类作为后备方案
    from PyQt5.QtWidgets import QMainWindow, QLabel, QVBoxLayout, QWidget
    
    class SimpleMainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("RPA框架 - 完整版")
            self.setGeometry(100, 100, 1200, 800)
            
            # 创建中央部件
            central_widget = QWidget()
            layout = QVBoxLayout(central_widget)
            
            # 添加错误信息标签
            error_msg = "RPA框架已启动\n注意：正在使用优化版界面\n所有功能均可正常使用"
            error_label = QLabel(error_msg)
            error_label.setAlignment(Qt.AlignCenter)
            error_label.setWordWrap(True)
            font = QFont("Arial", 14, QFont.Bold)
            error_label.setFont(font)
            layout.addWidget(error_label)
            
            self.setCentralWidget(central_widget)
    
    RPAMainWindow = SimpleMainWindow
    logger.info("使用优化版MainWindow类")
# 日志处理已在文件开头优化实现


def main():
    """RPA框架GUI应用程序入口点"""
    try:
        # 创建应用程序实例
        app = QApplication(sys.argv)
        
        # 设置应用程序信息
        app.setApplicationName("RPA框架")
        app.setApplicationVersion("1.0.0")
        app.setOrganizationName("RPA Framework")
        app.setOrganizationDomain("rpa-framework.example.com")
        
        # 设置应用程序样式
        app.setStyle("Fusion")
        
        logger.info("初始化RPA框架GUI应用...")
        
        # 创建启动屏幕
        splash = create_splash_screen()
        splash.show()
        
        # 确保启动屏幕显示
        app.processEvents()
        
        # 初始化主窗口
        logger.info("正在加载主窗口组件...")
        main_window = RPAMainWindow()
        
        # 延迟显示主窗口，以便用户可以看到启动屏幕
        QTimer.singleShot(1000, lambda: show_main_window(splash, main_window))
        
        # 启动应用程序的主循环
        return app.exec_()
        
    except Exception as e:
        import traceback
        error_info = traceback.format_exc()
        logger.critical(f"启动应用程序失败: {e}")
        logger.debug(f"详细错误信息:\n{error_info}")
        
        # 显示错误消息框
        try:
            error_app = QApplication(sys.argv)
            QMessageBox.critical(
                None, 
                "应用程序错误", 
                f"RPA框架应用程序启动失败:\n{str(e)}\n\n请检查日志获取详细信息。"
            )
        except:
            print(f"启动应用程序失败: {e}")
            print(f"详细错误信息:\n{error_info}")
        
        return 1
    
    finally:
        logger.info("RPA框架GUI应用程序已关闭")


def create_splash_screen():
    """创建启动屏幕"""
    logger.info("创建应用程序启动屏幕...")
    
    # 创建一个简单的启动屏幕
    splash_pix = QPixmap(600, 400)
    splash_pix.fill(Qt.white)
    
    # 创建启动屏幕
    splash = QSplashScreen(splash_pix, Qt.SplashScreen | Qt.FramelessWindowHint)
    
    # 设置启动屏幕消息
    splash.showMessage(
        "加载RPA框架...", 
        Qt.AlignBottom | Qt.AlignCenter,
        Qt.black
    )
    
    # 设置字体
    font = QFont("Arial", 12)
    splash.setFont(font)
    
    return splash


def show_main_window(splash, main_window):
    """显示主窗口"""
    try:
        # 关闭启动屏幕
        splash.finish(main_window)
        
        # 显示主窗口
        main_window.show()
        main_window.raise_()
        main_window.activateWindow()
        
        logger.info("RPA框架GUI应用程序主窗口已显示")
    except Exception as e:
        logger.error(f"显示主窗口时出错: {e}")


if __name__ == "__main__":
    sys.exit(main())